package com.ms3ds.deviceData.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ms3ds.common.core.domain.R;
import com.ms3ds.common.core.utils.DateUtils;
import com.ms3ds.deviceData.api.RemoteDeviceService;
import com.ms3ds.deviceData.api.domain.Device;
import com.ms3ds.mineInfo.api.*;
import com.ms3ds.mineInfo.api.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ms3ds.common.log.annotation.Log;
import com.ms3ds.common.log.enums.BusinessType;
import com.ms3ds.common.security.annotation.RequiresPermissions;
import com.ms3ds.deviceData.domain.MiningRecord;
import com.ms3ds.deviceData.service.IMiningRecordService;
import com.ms3ds.common.core.web.controller.BaseController;
import com.ms3ds.common.core.web.domain.AjaxResult;
import com.ms3ds.common.core.utils.poi.ExcelUtil;
import com.ms3ds.common.core.web.page.TableDataInfo;

/**
 * 矿石开采记录Controller
 * 
 * @author zlw
 * @date 2025-09-21
 */
@RestController
@RequestMapping("/miningRecord")
public class MiningRecordController extends BaseController
{
    @Autowired
    private IMiningRecordService miningRecordService;

    @Autowired
    private RemoteMineService remoteMineService;

    @Autowired
    private RemoteTeamService  remoteTeamService;

    @Autowired
    private RemoteTaskService remoteTaskService;

    @Autowired
    private RemoteWorkerService remoteWorkerService;

    @Autowired
    private RemoteAreaService remoteAreaService;

    @Autowired
    private RemoteOreTypeService remoteOreTypeService;

    /**
     * 查询矿石开采记录列表
     */
    @RequiresPermissions("deviceData:miningRecord:list")
    @GetMapping("/list")
    public TableDataInfo list(MiningRecord miningRecord)
    {
        startPage();
        List<MiningRecord> list = miningRecordService.selectMiningRecordList(miningRecord);
        return getDataTable(list);
    }


    @GetMapping("/getSystemPreviewSourceStore")
    public AjaxResult getSystemPreviewSourceStore(Long mineId){
        Map<String,List<Float>> map = new LinkedHashMap<>();
        R<List<Area>> remoteAreas = remoteAreaService.getAreaListByMineIdForRemote(mineId);
        if(remoteAreas!=null&&!remoteAreas.getData().isEmpty()){
            List<Area> areas = remoteAreas.getData();
            for(Area area:areas){
                List<Float> sources = new ArrayList<>();
                //设置区域实际总采集量
                sources.add(miningRecordService.getAreaTotalMiningRecord(area.getId()));
                //设置区域估计资源总量
                sources.add(area.getMineralQuantity());
                map.put(area.getAreaName(),sources);
            }
        }
        return success(map);
    }

    /**
     * 获取辅助策略下的运营分析数据，即查询每个区域的实际开采量
     * @param mineId
     * @return
     */
    @GetMapping("/getFuZhuYunYingFenxi")
    public AjaxResult getFuZhuYunYingFenxi(Long mineId){


        Map<String,Float> map = new LinkedHashMap<>();
        R<List<Area>> remoteAreas = remoteAreaService.getAreaListByMineIdForRemote(mineId);
        if(remoteAreas!=null&&!remoteAreas.getData().isEmpty()){
            List<Area> areas = remoteAreas.getData();
            for(Area area:areas){
                //设置区域实际总采集量
                map.put(area.getAreaName(),miningRecordService.getAreaTotalMiningRecord(area.getId()));
            }
        }
        return success(map);
    }

    @GetMapping("/getAnQuanShengChanYunYing")
    public AjaxResult getAnQuanShengChanYunYing(Long mineId){
        Map<String,Object> map = new LinkedHashMap<>();
        //开始查询年度开采任务
        //先获取矿山下的所有生产队
        R<List<Team>> remoteTeams = remoteTeamService.getAllTeamByMineIdForRemote(mineId);
        Float yearPlanNum = 0f;
        if(remoteTeams!=null&&remoteTeams.getData()!=null&&!remoteTeams.getData().isEmpty()){
            List<Team> teams = remoteTeams.getData();
            for(Team team:teams){
                //查询该生产队的年度任务
                R<Task> remoteTask = remoteTaskService.getYearTaskByTeamIdForRemote(team.getId());
                if(remoteTask!=null&&remoteTask.getData()!=null){
                    Task task = remoteTask.getData();
                    yearPlanNum+=task.getPlanMining();
                }
            }
        }
        //年度开采任务查询完成
        map.put("yearPlanMining",yearPlanNum);

        //开始查询昨日开采总量
        Float yestodayMiningNum = 0f;
        MiningRecord searchMiningRecordSum = new MiningRecord();
        //设置查询区域
        searchMiningRecordSum.setMineId(mineId);
        //设置查询时间，昨日
        Date[] yesterdays = DateUtils.getYesterdayRange();
        Map<String,Object> params = new HashMap<>();
        params.put("startTime",DateUtils.paraseString(yesterdays[0]));
        params.put("endTime",DateUtils.paraseString(yesterdays[1]));
        searchMiningRecordSum.setParams(params);
        yestodayMiningNum = miningRecordService.getMiningRecordSumByMineId(searchMiningRecordSum);
        //昨日开采总量查询完成
        map.put("yestodayMiningNum",yestodayMiningNum);

        //开始查询平均品位
        //先查询矿山信息
        R<Mine> remoteMine = remoteMineService.getMineByMineIdForRemote(mineId);
        Map<String,Float> pingWeiMap = new LinkedHashMap<>();
        if(remoteMine!=null&&remoteMine.getData()!=null){
            Mine mine = remoteMine.getData();
            //获取矿物种类信息
            String[] oreTypes = mine.getMinedMinerals().split(",");
            for(String oreTypeId:oreTypes){
                //获取矿物种类信息
                R<OreType> remoteOreType = remoteOreTypeService.getOreTypeByIdForremote(Long.valueOf(oreTypeId));
                if(remoteOreType!=null&&remoteOreType.getData()!=null){//查询到矿物信息才有后续操作
                    OreType oreType = remoteOreType.getData();
                    MiningRecord searchMiningRecord = new MiningRecord();
                    //设置查询时间，昨日
                    Date[] yesterdayRange = DateUtils.getYesterdayRange();
                    Map<String,Object> param = new HashMap<>();
                    param.put("startTime",DateUtils.paraseString(yesterdayRange[0]));
                    param.put("endTime",DateUtils.paraseString(yesterdayRange[1]));
                    searchMiningRecord.setParams(param);
                    //设置查询种类
                    searchMiningRecord.setOreId(oreType.getId());
                    //统计该种类昨日采集的平均品位
                    Float avgPingWei = miningRecordService.selectAvgPingWeiByOreId(searchMiningRecord);
                    if(avgPingWei!=null){
                        pingWeiMap.put(oreType.getOreTypeName(),avgPingWei*100);
                    }
                }
            }
        }
        //平均品位查询完成
        map.put("pingWei",pingWeiMap);
        return  success(map);
    }

    /**
     * 获取辅助决策页面的开采分析数据
     * @param mineId
     * @return
     */
    @GetMapping("/getFuZhuMiningRecord")
    public AjaxResult getFuZhuMiningRecord(Long mineId){
        Map<String,Float> map = new LinkedHashMap<>();
        //获取所有生产队信息
        R<List<Team>> remoteTeams = remoteTeamService.getAllTeamByMineIdForRemote(mineId);
        if(remoteTeams!=null&&!remoteTeams.getData().isEmpty()){
            List<Team> teams = remoteTeams.getData();
            for(Team team:teams){
                Float teamTotalMiningRecord = miningRecordService.getTeamTotalMiningRecord(team.getId());
                map.put(team.getTeamName(),teamTotalMiningRecord!=null?teamTotalMiningRecord:0);
            }
        }
        return success(map);
    }



    Integer workTime = 2;//工人工作时长
    float workMiningSpeed = 35.0f;//假设工人每小时最多采集35吨
    float averagePingWei = 0.30f;//假设平均品味的最值为百分之三十
    @GetMapping("/generateMiningRecord")
    public R<Boolean> generateMiningRecord()
    {
        //先获取全部矿山信息
        R<List<Mine>> remoteMineList = remoteMineService.getAllForRemote();
        if(remoteMineList!=null&&(!remoteMineList.getData().isEmpty())){
            List<Mine> mines = remoteMineList.getData();
            //遍历矿山
            for(Mine mine:mines){
                //设置当前矿山能挖去的矿种
                String[] minedMinerals = mine.getMinedMinerals().split(",");
                List<Long> oreTypeList = new ArrayList<>();
                for(String minedMineral:minedMinerals){
                    oreTypeList.add(Long.valueOf(minedMineral));
                }
                //获取该矿山的工作区域信息
                R<List<Area>> areaListForRemote = remoteAreaService.getAreaListByMineIdForRemote(mine.getId());
                List<Area> areas = new ArrayList<>();
                if(areaListForRemote==null||areaListForRemote.getData().isEmpty()){
                    return R.ok(false);
                }else{
                    areas = areaListForRemote.getData();
                }
                //获取矿山下的生产队信息
                R<List<Team>> remoteTeamList = remoteTeamService.getAllTeamByMineIdForRemote(mine.getId());
                if(remoteTeamList!=null&&(!remoteTeamList.getData().isEmpty())){
                    List<Team> teams = remoteTeamList.getData();
                    //遍历生产队
                    for(Team team:teams){
                        //获取开采任务信息
                        R<List<Task>> remoteTaskList = remoteTaskService.getTaskByTeamIdForRemote(team.getId());
                        List<Task> tasks = new ArrayList<>();
                        if(remoteTaskList==null||remoteTaskList.getData().isEmpty()){
                            return R.ok(false);
                        } else{
                            tasks =  remoteTaskList.getData();
                        }
                        //获取工人信息
                        R<List<Worker>> remoteWorkerList = remoteWorkerService.getWorkerByTeamIdForRemote(team.getId());
                        if(remoteWorkerList!=null&&(!remoteWorkerList.getData().isEmpty())){
                            List<Worker> workers = remoteWorkerList.getData();
                            for(Worker worker:workers){
                                if(worker.getStatus()==1&&worker.getAreaId()!=null){//如果工人在岗，并且有对应工作区域,说明已经工作了，需要休息
                                    worker.setStatus(0L);
                                    worker.setAreaId(null);
                                }else{//让没有工作的工人参与工作
                                    worker.setStatus(1L);
                                    //设置工作区域
                                    Area area = areas.get((int) (Math.random() * areas.size()));
                                    worker.setAreaId(area.getId());

                                    MiningRecord miningRecord = new MiningRecord();
                                    //设置挖矿人
                                    miningRecord.setAreaId(worker.getAreaId());//设置工作区域
                                    miningRecord.setWorkerId(worker.getId());
                                    //从矿物种类中随机选择一种
                                    miningRecord.setOreId(oreTypeList.get((int)(Math.random() * oreTypeList.size())));
                                    miningRecord.setStartTime(DateUtils.getNowDate());//开始工作
                                    miningRecord.setEndTime(DateUtils.addHours(DateUtils.getNowDate(), workTime));//工作两小时
                                    float rate = (float) (0.6 + Math.random() * (1.2 - 0.6));//假设工人工作效率在0.6-1.2之间
                                    miningRecord.setTotalWeight(workMiningSpeed*rate*workTime);//挖矿
                                    float ratePingwei = (float)(0.3 + Math.random() * (1.2 - 0.3));//假设品位变化在0.3-1.2之间
                                    miningRecord.setRealQuantity(miningRecord.getTotalWeight()*ratePingwei*averagePingWei);
                                    //插入数据,完成挖矿
                                    miningRecordService.insertMiningRecord(miningRecord);

                                    //开始更新开采计划数据
                                    for(Task task:tasks){
                                        Date startTime = task.getStartTime();
                                        Date endTime = null;
                                        if(task.getTaskType()==1){//年度任务
                                            endTime = DateUtils.addYears(startTime, 1);
                                        } else if(task.getTaskType()==2){//季度任务
                                            endTime = DateUtils.addMonths(startTime, 3);
                                        }else if(task.getTaskType()==3){//月度任务
                                            endTime = DateUtils.addMonths(startTime, 1);
                                        }else if(task.getTaskType()==4){//周度任务
                                            endTime = DateUtils.addDays(startTime, 7);
                                        } else if (task.getTaskType()==5) {//日度任务
                                            endTime = DateUtils.addDays(startTime, 1);
                                        }
                                        Date workTime = miningRecord.getStartTime();//开工时间
                                        if(workTime.after(startTime)&&workTime.before(endTime)){//如过工作时间在计划范围内，则记录开采量
                                            task.setRealMining(task.getRealMining() + miningRecord.getTotalWeight());
                                            //更新开采计划
                                            remoteTaskService.editTaskForRemote(task);
                                        }
                                    }
                                }
                                //更新工人信息
                                remoteWorkerService.editWorkerForRemote(worker);
                            }
                        }
                    }
                }
            }
        }
        return R.ok(true);
    }

    /**
     * 导出矿石开采记录列表
     */
    @RequiresPermissions("deviceData:miningRecord:export")
    @Log(title = "矿石开采记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MiningRecord miningRecord)
    {
        List<MiningRecord> list = miningRecordService.selectMiningRecordList(miningRecord);
        ExcelUtil<MiningRecord> util = new ExcelUtil<MiningRecord>(MiningRecord.class);
        util.exportExcel(response, list, "矿石开采记录数据");
    }

    /**
     * 获取矿石开采记录详细信息
     */
    @RequiresPermissions("deviceData:miningRecord:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(miningRecordService.selectMiningRecordById(id));
    }

    /**
     * 新增矿石开采记录
     */
    @RequiresPermissions("deviceData:miningRecord:add")
    @Log(title = "矿石开采记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MiningRecord miningRecord)
    {
        return toAjax(miningRecordService.insertMiningRecord(miningRecord));
    }

    /**
     * 修改矿石开采记录
     */
    @RequiresPermissions("deviceData:miningRecord:edit")
    @Log(title = "矿石开采记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MiningRecord miningRecord)
    {
        return toAjax(miningRecordService.updateMiningRecord(miningRecord));
    }

    /**
     * 删除矿石开采记录
     */
    @RequiresPermissions("deviceData:miningRecord:remove")
    @Log(title = "矿石开采记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(miningRecordService.deleteMiningRecordByIds(ids));
    }
}
